package com.devplatform.service.impl.article;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devplatform.mapper.article.ArticleInteractionsMapper;
import com.devplatform.mapper.article.UserArticleLikeMapper;
import com.devplatform.mapper.user.UserMapper;
import com.devplatform.pojo.article.Article;
import com.devplatform.pojo.user.User;
import com.devplatform.pojo.user.UserArticleLike;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.article.ArticleService;
import com.devplatform.service.article.UserArticleLikeService;
import com.devplatform.service.points.PointsDetailService;
import com.devplatform.util.MessageUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jnks03
 * @description 针对表【user_article_like】的数据库操作Service实现
 * @createDate 2025-09-29 09:41:47
 */
@Service
@RequiredArgsConstructor
public class UserArticleLikeServiceImpl extends ServiceImpl<UserArticleLikeMapper, UserArticleLike>
        implements UserArticleLikeService {
    private final UserArticleLikeMapper mapper;
    private final ArticleInteractionsMapper interactionsMapper;
    private final UserMapper userMapper;
    private final MessageUtil messageUtil;
    private final ArticleService articleService;
    private final PointsDetailService pointsDetailService;

    //新增用户文章点赞关系
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DataVo likes(UserArticleLike userArticleLike) {
        Long userId = userArticleLike.getUserId();
        Long articleId = userArticleLike.getArticleId();
        LambdaQueryWrapper<UserArticleLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserArticleLike::getUserId, userId).eq(UserArticleLike::getArticleId, articleId);
        //查询是否存在对应的用户文章关系
        UserArticleLike hasLiked = mapper.selectOne(queryWrapper);
        if (hasLiked != null) {
            //存在，删除关系并取消点赞
            mapper.deleteById(hasLiked.getId());
            interactionsMapper.decrementLikes(articleId);
            return DataVo.ok("取消点赞成功");
        } else {
            userArticleLike.setCreateTime(LocalDateTime.now());
            mapper.insert(userArticleLike);
            interactionsMapper.incrementLikes(articleId);
            Long authorId = articleService.getAuthorIdByArticleId(articleId);
            pointsDetailService.ArticlePoints(authorId, "ARTICLE_LIKE");

            User liker = userMapper.selectById(userId);
            String likerName = liker != null ? liker.getUsername() : "用户";

            Article article = articleService.getById(articleId); // 从ArticleService获取文章信息
            String articleTitle = article != null ? article.getTitle() : "未知文章";

            String title = "新点赞通知";
            String content = String.format("用户【%s】点赞了你的文章《%s》", likerName, articleTitle);

            Map<String, Object> extraData = new HashMap<>();
            extraData.put("articleId", articleId); // 文章ID，便于跳转
            extraData.put("likerId", userId); // 点赞用户ID，便于查看

            messageUtil.sendSystemMessage(authorId, title, content, extraData);

            return DataVo.ok("点赞成功");
        }
    }

    @Override
    public DataVo<Boolean> isLiked(Long userId, Long articleId) {
        LambdaQueryWrapper<UserArticleLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserArticleLike::getUserId, userId)
                .eq(UserArticleLike::getArticleId, articleId);

        // 统计符合条件的记录数（>0表示已点赞）
        int count = Math.toIntExact(mapper.selectCount(queryWrapper));
        return DataVo.ok(count > 0);
    }

}




